package com.sunshine.wrongquestionset.view

import android.content.Context
import android.graphics.Color
import android.view.LayoutInflater
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.github.mikephil.charting.charts.LineChart
import com.github.mikephil.charting.components.AxisBase
import com.github.mikephil.charting.components.Description
import com.github.mikephil.charting.components.XAxis
import com.github.mikephil.charting.data.Entry
import com.github.mikephil.charting.data.LineData
import com.github.mikephil.charting.data.LineDataSet
import com.github.mikephil.charting.formatter.ValueFormatter
import com.google.android.material.bottomsheet.BottomSheetBehavior
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.sunshine.wrongquestionset.R
import com.sunshine.wrongquestionset.activity.exercise_history.ExerciseHistoryRecyclerAdapter
import com.sunshine.wrongquestionset.callback.QuestionOptionsListener
import com.sunshine.wrongquestionset.room.entity.WrongQuestionBean
import com.sunshine.wrongquestionset.utils.QuestionFamiliarityBean
import com.zzhoujay.glideimagegetter.GlideImageGetter
import com.zzhoujay.richtext.ImageHolder
import com.zzhoujay.richtext.RichText
import com.zzhoujay.richtext.RichType
import java.text.DecimalFormat

/**
 * @author sunshine
 * @date 2021/4/11
 */
object QuestionContentBottomSheetDialog {

    //百分数保留2位
    private val decimalFormat = DecimalFormat("0.##%")

    /**
     * @param titlePath 题干
     * @param answerPath 答案
     * @param infoText 题目说明
     */
    fun show(
        context: AppCompatActivity,
        titlePath: String,
        answerPath: String,
        infoText: String,
        questionFamiliarityBean: QuestionFamiliarityBean?,
        exerciseHistoryList: List<WrongQuestionBean>?,
        callback: QuestionOptionsListener
    ) {
        val bottomSheetDialog = BottomSheetDialog(context, R.style.Theme_Design_BottomSheetDialog)
        val view = LayoutInflater.from(context).inflate(R.layout.view_question_content, null, false)
        val titleContent: TextView = view.findViewById(R.id.textView_title_content)
        val answerContent: TextView = view.findViewById(R.id.textView_answer_content)
        val lineChart: LineChart = view.findViewById(R.id.lineChart_familiarity)
        val recyclerViewHistory: RecyclerView = view.findViewById(R.id.recyclerView_history)
        val info: TextView = view.findViewById(R.id.textView_question_info)
        val delete: ImageView = view.findViewById(R.id.imageView_delete)
        val edit: ImageView = view.findViewById(R.id.imageView_edit)

        delete.setOnClickListener {
            callback.onDelete()
            bottomSheetDialog.dismiss()
        }

        edit.setOnClickListener {
            callback.onEdit()
            bottomSheetDialog.dismiss()
        }

        RichText
            .from(titlePath.replace("\n", "\n\n"))
            .type(RichType.markdown)
            .scaleType(ImageHolder.ScaleType.fit_auto)
            .into(titleContent)

//        titleContent.post {
//            Thread {
//                val spanned = MarkDown.fromMarkdown(titlePath.replace("\n", "\n\n"), { source ->
//                    try {
//                        //主线程执行，效果不是很好
//                        val drawable = Drawable.createFromPath(source)
//                        drawable?.setBounds(0, 0, drawable.intrinsicWidth, drawable.intrinsicHeight)
//                        drawable
//                    }catch (e: Exception) {
//                        //Snackbar.make(add_question_expend_root, getString(R.string.load_image_fail_2), Snackbar.LENGTH_SHORT).show()
//                        null
//                    }
//                }, titleContent)
//                titleContent.post {
//                    titleContent.text = spanned
//                }
//            }.start()
//        }

        RichText
            .from(answerPath.replace("\n", "\n\n"))
            .type(RichType.markdown)
            .scaleType(ImageHolder.ScaleType.fit_auto)
            .into(answerContent)
//        answerContent.post {
//            Thread {
//                val spanned = MarkDown.fromMarkdown(answerPath.replace("\n", "\n\n"), { source ->
//                    try {
//                        //主线程执行，效果不是很好
//                        val drawable = Drawable.createFromPath(source)
//                        drawable?.setBounds(0, 0, drawable.intrinsicWidth, drawable.intrinsicHeight)
//                        drawable
//                    }catch (e: Exception) {
//                        //Snackbar.make(add_question_expend_root, getString(R.string.load_image_fail_2), Snackbar.LENGTH_SHORT).show()
//                        null
//                    }
//                }, answerContent)
//                answerContent.post {
//                    answerContent.text = spanned
//                }
//            }.start()
//        }

        val lineDataSet = LineDataSet(questionFamiliarityBean?.entryList, "熟悉程度")

        //设置折线的配置
        lineDataSet.apply {
            //折线过渡为圆角
            mode = LineDataSet.Mode.CUBIC_BEZIER
            //折线的颜色，设置为主题色
            color = context.getColor(R.color.google_blue_600)
            //圆点颜色
            setCircleColor(context.getColor(R.color.google_blue_600))

            valueFormatter = object : ValueFormatter() {
                override fun getPointLabel(entry: Entry?): String {
                    if (entry == null) return ""
                    return decimalFormat.format(entry.y)
                }
            }

            valueTextSize = 10.0f
        }

        val lineData = LineData(lineDataSet)

        val description = Description()
        description.text = "题目熟悉程度折线图"

        //整图的配置
        lineChart.apply {
            data = lineData
            setDescription(description)
            //是否绘制X轴上的网格线（背景里面的竖线）
            xAxis.setDrawGridLines(false)
            //是否绘制Y轴上的网格线（背景里面的横线）
            axisLeft.setDrawGridLines(false)

            //设置不支持手势缩放
            setScaleEnabled(false)

            //X轴位置
            xAxis.position = XAxis.XAxisPosition.BOTTOM

            //设置X轴个数
            xAxis.setLabelCount(questionFamiliarityBean?.entryList?.size ?: 0, true)
            //设置Y轴个数
            axisLeft.setLabelCount(6, false)

            //设置X轴坐标为整数时显示
            xAxis.valueFormatter = object : ValueFormatter() {
                override fun getAxisLabel(value: Float, axis: AxisBase?): String {
                    if (questionFamiliarityBean == null) return ""
                    return questionFamiliarityBean.xTimeMap[value.toInt()]?:""
                }
            }

            axisLeft.valueFormatter = object : ValueFormatter() {
                override fun getAxisLabel(value: Float, axis: AxisBase?): String {
                    return decimalFormat.format(value)
                }
            }

            //隐藏右边的Y轴
            axisRight.isEnabled = false
            //设置y轴最小从0开始
            axisLeft.mAxisMinimum = 0.0f
            //设置最大值
            axisLeft.mAxisMaximum = 1.0f

            //Y轴动画
            animateY(1000)

            invalidate()
        }

        val adapter = ExerciseHistoryRecyclerAdapter(exerciseHistoryList)
        recyclerViewHistory.layoutManager = LinearLayoutManager(context)
        recyclerViewHistory.adapter = adapter

        //设置题目信息文字
        info.text = infoText

        bottomSheetDialog.setContentView(view)
        bottomSheetDialog.window?.findViewById<FrameLayout>(R.id.design_bottom_sheet)?.setBackgroundColor(
            Color.TRANSPARENT)

        bottomSheetDialog.show()
    }

    fun showWrongQuestion(
        context: Context,
        titlePath: String,
        answerPath: String,
        myAnswerPath: String,
        infoText: String
    ) {
        val bottomSheetDialog = BottomSheetDialog(context, R.style.Theme_Design_BottomSheetDialog)
        val view = LayoutInflater.from(context).inflate(R.layout.view_wrong_question_content, null, false)
        val titleContent: TextView = view.findViewById(R.id.textView_title_content)
        val answerContent: TextView = view.findViewById(R.id.textView_answer_content)
        val myAnswerContent: TextView = view.findViewById(R.id.textView_my_answer_content)
        val info: TextView = view.findViewById(R.id.textView_question_info)

        RichText
            .from(titlePath.replace("\n", "\n\n"))
            .type(RichType.markdown)
            .scaleType(ImageHolder.ScaleType.fit_auto)
            .into(titleContent)

//        titleContent.post {
//            Thread {
//                val spanned = MarkDown.fromMarkdown(titlePath.replace("\n", "\n\n"), { source ->
//                    try {
//                        //主线程执行，效果不是很好
//                        val drawable = Drawable.createFromPath(source)
//                        drawable?.setBounds(0, 0, drawable.intrinsicWidth, drawable.intrinsicHeight)
//                        drawable
//                    }catch (e: Exception) {
//                        //Snackbar.make(add_question_expend_root, getString(R.string.load_image_fail_2), Snackbar.LENGTH_SHORT).show()
//                        null
//                    }
//                }, titleContent)
//                titleContent.post {
//                    titleContent.text = spanned
//                }
//            }.start()
//        }

        RichText
            .from(answerPath.replace("\n", "\n\n"))
            .type(RichType.markdown)
            .scaleType(ImageHolder.ScaleType.fit_auto)
            .imageClick { _, _ -> }
            .into(answerContent)

//        answerContent.post {
//            Thread {
//                val spanned = MarkDown.fromMarkdown(answerPath.replace("\n", "\n\n"), { source ->
//                    try {
//                        //主线程执行，效果不是很好
//                        val drawable = Drawable.createFromPath(source)
//                        drawable?.setBounds(0, 0, drawable.intrinsicWidth, drawable.intrinsicHeight)
//                        drawable
//                    }catch (e: Exception) {
//                        //Snackbar.make(add_question_expend_root, getString(R.string.load_image_fail_2), Snackbar.LENGTH_SHORT).show()
//                        null
//                    }
//                }, answerContent)
//                answerContent.post {
//                    answerContent.text = spanned
//                }
//            }.start()
//        }


        RichText
            .from(myAnswerPath.replace("\n", "\n\n"))
            .type(RichType.markdown)
            .scaleType(ImageHolder.ScaleType.fit_auto)
            .into(myAnswerContent)

//        myAnswerContent.post {
//            Thread {
//                val spanned = MarkDown.fromMarkdown(myAnswerPath.replace("\n", "\n\n"), { source ->
//                    try {
//                        //主线程执行，效果不是很好
//                        val drawable = Drawable.createFromPath(source)
//                        drawable?.setBounds(0, 0, drawable.intrinsicWidth, drawable.intrinsicHeight)
//                        drawable
//                    }catch (e: Exception) {
//                        //Snackbar.make(add_question_expend_root, getString(R.string.load_image_fail_2), Snackbar.LENGTH_SHORT).show()
//                        null
//                    }
//                }, myAnswerContent)
//                myAnswerContent.post {
//                    myAnswerContent.text = spanned
//                }
//            }.start()
//        }

        //设置题目信息文字
        info.text = infoText

        bottomSheetDialog.setContentView(view)
        bottomSheetDialog.window?.findViewById<FrameLayout>(R.id.design_bottom_sheet)?.setBackgroundColor(
            Color.TRANSPARENT)
        bottomSheetDialog.show()
    }

}